<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>chat</title>
    <script type="text/javascript">
        var htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
        if (htmlWidth > 750) {
            htmlWidth = 750
        }
        var htmlDom = document.getElementsByTagName('html')[0];
        htmlDom.style.fontSize = htmlWidth / 30 + 'px';
    </script>
    <script src="https://cdn.bootcdn.net/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/highlight.js/11.6.0/styles/a11y-dark.min.css" rel="stylesheet">
    <link href="index.css" rel="stylesheet">
    <script src="marked.min.js"></script>
    <script>hljs.initHighlightingOnLoad();</script>

</head>
<body>
<div class="container">
    <div class="chat" id="chat">
        <div class="scroll-content">
            <div class="chat-content" id="chatContent">
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="input_01">
            <textarea class="question" maxlength="1000" id="quest" type="text" placeholder="输入你的问题" onblur="this.placeholder='输入你的问题'" onfocus="this.placeholder=''"></textarea>
            <input class="submit" name="submit" onclick="submit_opt()" type="button" value="提交">
        </div>
    </div>

</div>

<script type="text/javascript">
    var rendererMD = new marked.Renderer();
    marked.setOptions({
        renderer: rendererMD,
        gfm: false,
        tables: true,
        breaks: true,
        pedantic: false,
        sanitize: false,
        smartLists: false,
        smartypants: false,
        highlight: function (code) {
            return hljs.highlightAuto(code).value;}
    });
    var answerQuestions = [
        {
            headImg: './images/12px.svg',
            authorName: '易点通机器人',
            message: '这里是易点通机器人',
            type: 'plain',
            position: 'left'
        },//type: 'plain'正常的文档，picture图片
        {
            headImg: './images/12px.svg',
            authorName: '易点通机器人',
            message: '欢迎使用此功能',
            type: 'plain',
            position: 'left'
        },
        {
            headImg: './images/12px.svg',
            authorName: '易点通机器人',
            message: '有什么问题可以直接询问',
            type: 'plain',
            position: 'left'
        },

    ]
    var myQuestion = {message: '', position: 'right'}
    var isSendMsg = false;//是否发送了消息
    var scrollContent = document.getElementsByClassName('scroll-content')[0];
    var chatContent = document.getElementById('chatContent');
    var questcontent = document.getElementById("quest");

    //创建问答div
    function createDiv(messageObj) {
        let child = null
        if (messageObj.position == 'left') {
            let tag = messageObj.type == 'plain' ? `<pre id="parenthljs">`+messageObj.message +'</pre>' : '<img class="chat-img" src=" ' + messageObj.message + '" />'
            let bubble = messageObj.type == 'plain' ? 'bubble-default' : 'bubble-image';
            child = `

                    <div class="message others">
                        <div class="head-img">
                            <img src="${messageObj.headImg}" alt="头像" />
                        </div>
                        <div class="content">
                           <p class="author-name">${messageObj.authorName}</p>
                            <div class="bubble ${bubble} left" >
                                <div class="bubble-cont">
                                    <div class="${messageObj.type}">
                                        ${tag}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                `
        } else {
            child = `

                    <div class="message me">

                        <div class="content">

                            <div class="bubble bubble-default right" >
                                <div class="bubble-cont">
                                    <div class="plain">
                                       <pre>${messageObj.message}</pre>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `
        }
        let oDiv = document.createElement('div');
        oDiv.className = 'clearfix';
        oDiv.innerHTML = child;
        chatContent.appendChild(oDiv);
        hljs.initHighlighting()
    }

    function submit_opt() {
        let mess = questcontent.value.trim();
        if("" == mess){
            return;
        }
        myQuestion.message = mess;
        createDiv(myQuestion);
        scrollContent.scrollTop = scrollContent.scrollHeight;
        questcontent.value='';
        responseMess(mess);
    }

    let index = 0;
    function answer_opt(obj) {
        isSendMsg = true;
        let time = Math.random() * 2500;
        setTimeout(() => {
            createDiv(obj[index]);
            index++;
            if (index <= obj.length - 1) {
                answer_opt(obj)
            } else {
                index = 0;
                isSendMsg = false;
            }
            scrollContent.scrollTop = scrollContent.scrollHeight;
        }, time)
    }

    function replaceStr(str){
        let regex1 = /```/g;
        let regex2 = /```\n{2,}/g;
        let index1 = 1;
        str = str.replace(/\t{1,}/g,'\n');
        str = str.replace(/\x20{4,}\`\`\`/g,'\`\`\`');
        str = str.replace(regex1,function(){index1++;return index1%2?'```\n':arguments[0]});
        str = str.replace(regex2,'```\n');
        return str;
    }
    function preReplace(str){
        str = str.replace(/\`/g,'\'');
        str = str.replace(/\'\'\'/g,'\`\`\`');
        return str;
    }

    function responseMess(mess){
        let xmlhttp;
        if (mess.length == 0){
            return;
        }
        if (window.XMLHttpRequest)
        {
            // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                xmlhttp=new XMLHttpRequest();
        }
        else
        {
            // IE6, IE5 浏览器执行代码
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                let answerContent = xmlhttp.responseText;
                answerContent = preReplace(answerContent);
                answerContent = JSON.parse(answerContent);

                for (let i = 0; i < answerContent.length; i++){
                    let answerMess = answerContent[i].answer;
                    let sendContent = answerQuestions[0];
                    answerMess = replaceStr(answerMess);
                    sendContent.message = marked(answerMess);
                    createDiv(sendContent);
                    scrollContent.scrollTop = scrollContent.scrollHeight;
                }
            }
        }
        xmlhttp.open("GET","http://124.70.190.249/robot/api/?q="+mess,true);
        xmlhttp.send();
    }

    window.onload = function () {
        answer_opt(answerQuestions);
    }

</script>
</body>
</html>